﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Demo.Model.Other;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using SqlSugar;
using System.Text;

namespace Demo.Api.Config
{
    /// <summary>
    /// 扩展类
    /// </summary>
    public static class HostBuilderExtend
    {
        public static void Register(this WebApplicationBuilder builder)
        {
            var basePath = AppContext.BaseDirectory;
            //引入配置文件
            var _config = new ConfigurationBuilder()
                             .SetBasePath(basePath)
                             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                             .Build();
            builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
            {
                #region 注入数据库
                var dbtype = DbType.SqlServer;
                if (_config.GetConnectionString("DbType") == "mysql")
                {
                    dbtype = DbType.MySql;
                }
                builder.Register<ISqlSugarClient>(context =>
                {
                    SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        //连接字符串
                        ConnectionString = _config.GetConnectionString("db_master"),
                        DbType = dbtype,
                        IsAutoCloseConnection = true
                    });
                    //支持sql语句的输出，方便排查问题
                    db.Aop.OnLogExecuted = (sql, par) =>
                    {
                        Console.WriteLine("\r\n");
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine($"时间：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine($"Sql语句：{sql}");
                        Console.WriteLine("===========================================================================");
                    };

                    return db;
                });
                #endregion

                //注册接口实现层
                builder.RegisterModule(new AutofacModuleRegister());
            });
            builder.Services.AddControllersWithViews()
                .AddNewtonsoftJson(options =>
                {
                    // 首字母小写(驼峰样式)
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    // 时间格式化
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    // 忽略循环引用
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                });
            //注册Redis缓存
            builder.Services.AddSingleton<IRedis, Redis>();
            #region 注册log4net 日志 
            builder.Logging.AddLog4Net("Config/log4net.Config");
            #endregion
            //AutoMapper映射
            builder.Services.AddAutoMapper(typeof(AutoMapperConfigs));
            //注册Jwt
            builder.Services.Configure<JWTTokenOptions>(builder.Configuration.GetSection("JWTTokenOptions"));
            #region JWT校验
            //第二步，增加鉴权逻辑
            JWTTokenOptions tokenOptions = new JWTTokenOptions();
            builder.Configuration.Bind("JWTTokenOptions", tokenOptions);
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//Scheme
             .AddJwtBearer(options =>  //这里是配置的鉴权的逻辑
             {
                 options.TokenValidationParameters = new TokenValidationParameters
                 {
                     //JWT有一些默认的属性，就是给鉴权时就可以筛选了
                     ValidateIssuer = true,//是否验证Issuer
                     ValidateAudience = true,//是否验证Audience
                     ValidateLifetime = true,//是否验证失效时间
                     ValidateIssuerSigningKey = true,//是否验证SecurityKey
                     ValidAudience = tokenOptions.Audience,//
                     ValidIssuer = tokenOptions.Issuer,//Issuer，这两项和前面签发jwt的设置一致
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey))//拿到SecurityKey 
                 };
             });
            #endregion
            //添加跨域策略
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", opt => opt.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().WithExposedHeaders("X-Pagination"));
            });
           
            builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //var aa = _config.GetConnectionString("Redis");
            //Redis工具初始化
            RedisHelper.Initialization(new CSRedis.CSRedisClient(_config.GetConnectionString("Redis")));
            
        }
    }
}
